package testpaper

import (
	"fmt"
	"time"
	pb "./protobuf"
	"change.tm/microservice"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

var conn *grpc.ClientConn
var client pb.TestpaperClient

func DataSync( in int) (*pb.DataSyncReply, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()
	a:=pb.Tablename(in)
	result, err := client.DataSync(ctx, &pb.DataSyncRequest{Tablename:a})
	// 进行远程调用
	if err != nil {
		fmt.Printf("ceshi",err)
		return nil, nil
	}
	// 超时取消本次会话
	return result, nil
}
func AddUserKnowledge(UserknowledgepointID ,CourseID ,SyllabusKnowledgePointID,Userid string,AddTime,IsRight int32) (*pb.AddUserKnowledgeReply, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	var dat=pb.Userknowledgepoint{
		UserknowledgepointID:UserknowledgepointID,
		CourseID:CourseID,
		SyllabusKnowledgePointID:SyllabusKnowledgePointID,
		Userid:Userid,
		AddTime:AddTime,
		IsRight:IsRight,
	}
	result, err := client.AddUserKnowledge(ctx, &dat)
	// 进行远程调用
	if err != nil {
		return nil, err
	}
	// 超时取消本次会话
	return result, nil
}

	func CreateTestpaper(Userid ,CreateTestpaperID,Courseid ,TestpaperRuleID  string,Allnum,Newnum,Reviewnum,Wrongnum,Easy,Middle,Diff,Type int32) (*pb.CreateTestpaperReply, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
	defer cancel()
	var dat=pb.CreateTestpaperRequest{
		Userid:Userid,
		CreateTestpaperID:CreateTestpaperID,
		Courseid:Courseid,
		TestpaperRuleID:TestpaperRuleID,
		Type:Type,
		Role:&pb.Role{
			Allnum:Allnum,
			Newnum:Newnum,
			Wrongnum:Wrongnum,
			Reviewnum:Reviewnum,
			Easy:Easy,
			Middle:Middle,
			Diff:Diff,
		},
	}
	result, err := client.CreateTestpaper(ctx, &dat)
	// 进行远程调用
	if err != nil {
		return nil, err
	}
	// 超时取消本次会话
	return result, nil
}

func Connect() (*grpc.ClientConn, error) {
	var err error
	conn, err = microservice.CreateSimpleClient("testpaper")
	// 创建连接客户端
	client = pb.NewTestpaperClient(conn)
	if err != nil {
		return nil, err
	}
	// defer conn.Close()
	// 函数结束时自动断开连接，在频繁通信时可以考虑不断开连接，对连接对象进行复用，提高效率。
	return conn, nil
}